package com.tianpengtech.front.web.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.common.ip.IpInfo;
import com.tianpengtech.common.ip.IpUtil;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.pay.weixin.config.WXPayConfigImpl;

public class TaskCountService {

	
	public Fair getFairInfoByCode(String code ){
		
		String sql="select f.* from "+TaskWh.dao.tableName()+" as tw,"+Fair.dao.tableName()+" as f where tw.code=? and tw.wh_id=f.id limit 1";
		return Fair.dao.findFirst(sql,code);
	}
	
	
	public List<Record> getCommentsByTask(int taskid,int fair_id){
		String sql="select * from  fair_h5_comments where task_id=? and fair_id=? order by id desc";
		return Db.find(sql,taskid,fair_id);
	}
	
	
	public void saveComments(String ip,int task_id,String fromUserNickName,String fromUserUrl,
			String toUserNickName,String toUserUrl,String comment,int fair_id){
		
		//ip="27.38.119.45";
		if(StringUtils.isEmpty(fromUserNickName)){
			fromUserNickName = gernerateNickName(ip);
		}
		if(StringUtils.isEmpty(fromUserUrl)){
			fromUserUrl="/upload/avatar/x.jpg";
		}
		if(StringUtils.isEmpty(toUserUrl)){
			toUserUrl="/upload/avatar/x.jpg";
		}
		Record record = new Record();
		record.set("from_user_nickname", fromUserNickName);
		record.set("from_user_url", fromUserUrl);
		record.set("to_user_nickname", toUserNickName);
		record.set("to_user_url", toUserUrl);
		record.set("comment", filterEmoji(comment));
		record.set("task_id", task_id);
		record.set("fair_id", fair_id);
		Db.save("fair_h5_comments", record);
	}


	public String gernerateNickName(String ip) {
		String fromUserNickName;
		IpInfo info= IpUtil.getIpInfo(ip);
//		String result = HttpKit.get("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip="+ip);
//		result = result.replace("var remote_ip_info = ", "");
//		result = result.replace(";", "");
//		JSONObject obj = JSONObject.parseObject(result);
		if(info!=null){
			String city = info.getCity()==null?"":info.getCity();
			fromUserNickName=info.getProvince()+city+"用户["+ip+"]";
		}else{
			fromUserNickName="内网用户";
		}
		return fromUserNickName;
	}
	
	
	public  Map<String,Object> getUserInfoFromWeixin(String code,String ip) {
		Map<String,Object> userInfoMap = new HashMap<String,Object>();
		try {
			String secret="50b84a91daf18ddb79eed15546108a1a";
			String appId = WXPayConfigImpl.getInstance().getAppID();
			String accessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
			String tokenResult = HttpKit.get(accessTokenUrl);
			JSONObject tokenObj = JSONObject.parseObject(tokenResult);
			userInfoMap.put("nickName",gernerateNickName(ip));
			userInfoMap.put("avatarUrl","/upload/avatar/x.jpg");
			
			
			System.out.println(tokenObj);
			
			if(tokenObj.getString("access_token")!=null){
//				String accessToken = "4_TKN9MikIJMgHkDUW6tYxQYCU9RwcRZvcWffXUcGlxb2NjBHFwJnyPI7M4TVecZoVNw_YVWZjOgEP2l3ijFyT7w";
//				String openId = "oaA0n1D0c-jBdiLXCIhOA1vrV8YE";
				
				String accessToken = tokenObj.getString("access_token");
				String refreshToken = tokenObj.getString("refresh_token");
				String openId = tokenObj.getString("openid");
				
				//刷新token值
				String refreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+appId+"&grant_type=refresh_token&refresh_token="+refreshToken;
				String refreshResult = HttpKit.get(refreshUrl);
				JSONObject refreshObj = JSONObject.parseObject(refreshResult);
				System.out.println(refreshObj);
				if(refreshObj!=null){
					String refresh_access_token = refreshObj.getString("access_token");
					String refresh_open_id = refreshObj.getString("openid");
					String userInfoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+refresh_access_token+"&openid="+refresh_open_id+"&lang=zh_CN";
					String userInfoResult = HttpKit.get(userInfoUrl);
					JSONObject userInfo = JSONObject.parseObject(userInfoResult);
					System.out.println(userInfo);
					userInfoMap.put("nickName", filterEmoji(userInfo.getString("nickname")));
					userInfoMap.put("avatarUrl", userInfo.getString("headimgurl"));
				}
			}
		} catch (Exception e) {
			userInfoMap.put("nickName",gernerateNickName(ip));
			userInfoMap.put("avatarUrl","/upload/avatar/x.jpg");
		}
		return userInfoMap;
	}
	
	private String filterEmoji(String source){
		if (source == null) {
            return source;
        }
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher emojiMatcher = emoji.matcher(source);
        if (emojiMatcher.find()) {
            source = emojiMatcher.replaceAll("");
            return source;
        }
        return source;
	}
	
	
	public static void main(String[] args) {
		String result = HttpKit.get("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=219.159.108.221");
		result = result.replace("var remote_ip_info = ", "");
		result = result.replace(";", "");
		System.out.println(result);
		System.out.println(JSONObject.parse(result));
	}
	
	public Record getTaskClickInfo(String code){
		String sql="select click_num,reason from fair_task_wh  where code=? limit 1";
		return Db.findFirst(sql,code);
	}
	
	public  String  getRecommandReason(long wh_id){
		
		String sql="";
		String reason="看过来，这里最精彩，跟我一起做像样的网红!!!";
		return reason;
	}
}
